package com.quanyan.authority.web;

import com.lefu.commons.utils.Page;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.authority.cache.AuthorityRedisTemplate;
import com.quanyan.authority.constants.AuthorityConstants;
import com.quanyan.authority.mapper.RoleMenuMapper;
import com.quanyan.authority.mapper.TbOrganizationMapper;
import com.quanyan.authority.model.db.*;
import com.quanyan.authority.model.request.ReqLogin;
import com.quanyan.authority.model.request.ReqAdminUser;
import com.quanyan.authority.model.response.RespLogin;
import com.quanyan.authority.service.AdminUserService;
import com.quanyan.authority.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * Created by Administrator on 2016/8/4.
 */
@RestController
@RequestMapping("/admin/api/authority/adminUser/api/")
public class AdminUserController extends BaseController<ReqAdminUser>{

    private static final Logger logger = LoggerFactory.getLogger(AdminUserController.class);

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private MenuService menuService;


    @Autowired
    private TbOrganizationMapper tbOrganizationMapper;

    @Autowired
    private AuthorityRedisTemplate authorityRedisTemplate;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @RequestMapping(value = "login",method = RequestMethod.POST)
    public APIResponse adminUserLogin(@RequestBody @Valid ReqLogin reqLogin,BindingResult bindingResult,HttpServletRequest request){
        if (bindingResult.hasErrors())
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        logger.info("登录参数{}",reqLogin.toString());
        TbAdminUser tbAdminUser = adminUserService.login(reqLogin);
        if(tbAdminUser == null)
            return APIResponse.returnFail("用户名密码不正确！");
        request.getSession().setAttribute(AuthorityConstants.USER_SESSION_KEY,tbAdminUser);
        RespLogin respLogin = menuService.getUserMenuNew(tbAdminUser.getId());
        respLogin.setRespAdminUser(tbAdminUser);
        logger.info("登录返回{}",respLogin.toString());
        authorityRedisTemplate.set(AuthorityConstants.ADMIN_USER_REDIS_KEY + tbAdminUser.getId().toString(),tbAdminUser);
        return APIResponse.returnSuccess(respLogin);
    }

    @RequestMapping(value = "logout",method = RequestMethod.POST)
    public APIResponse adminUserLogout(HttpServletRequest request){
        String uid = (String)request.getAttribute("adminUid");
        authorityRedisTemplate.delteKey(AuthorityConstants.ADMIN_USER_REDIS_KEY + uid);
        request.getSession().invalidate();
        return APIResponse.returnSuccess();
    }


    @Override
    @RequestMapping(value = "save",method = RequestMethod.POST)
    public APIResponse save(@RequestBody @Valid ReqAdminUser reqAdminUser, BindingResult bindingResult) {
        try {

            adminUserService.add(reqAdminUser);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @Override
    @RequestMapping(value = "query",method = RequestMethod.POST)
    public APIResponse query(@RequestBody @Valid ReqAdminUser reqAdminUser) {
        try {
            Page page = adminUserService.findAll(reqAdminUser, reqAdminUser);
            return APIResponse.returnSuccess(page);
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }

    @Override
    @RequestMapping(value = "queryById",method = RequestMethod.POST)
    public APIResponse queryById(@RequestBody Map map) {
        try {
            Integer id = Integer.valueOf(map.get("id").toString());
            if( id == null )
                return APIResponse.returnFail("id不能为空！");

            List<TbRole> roleList = adminUserService.getUserRole(id);
            TbAdminUser tbAdminUser = adminUserService.findById(id);
            Map<String,Object> result = new HashMap<>();
            result.put("roleList",roleList);
            result.put("tbAdminUser",tbAdminUser);
            if(tbAdminUser.getDeptId() != null)
                result.put("dept",tbOrganizationMapper.selectByPrimaryKey(tbAdminUser.getDeptId()).getName());
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }

    @Override
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public APIResponse update(@RequestBody ReqAdminUser reqAdminUser) {
        try {
            adminUserService.update(reqAdminUser);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    @Override
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public APIResponse deleteById(@RequestBody Map map) {
        try {
            Integer id = Integer.valueOf(map.get("id").toString());
            if(id == null)
                return APIResponse.returnFail("id不能为空！");
            adminUserService.del(id);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }


    @RequestMapping(value = "monitor",method = RequestMethod.POST)
    public APIResponse monitor(HttpServletRequest request){
        return APIResponse.returnSuccess();
    }


}
